let exec = function () {
  return {
    provCode: '',
    provText: '',
    cityCode: '',
    cityText: '',
    cityData: '',
    districtText: '',
    districtData: '',
    area: '',
    areaIndex: '',
    fileData: [],
    fileArr: [],
    getSmsObj: {
      mobile: '',
      captcheCode: '',
      captchaKey: ''
    },
    requiredArr: {},
    params: {
      pageId: Number($('#micropageid').val()),
      formId: Number($('#formid').val()),
      data: []
    },
    init: function () {
      let me = this
      me.submitClick()
      me.initArea()
      me.getFileData()
      if($('#smsCode').length > 0) {
        me.getCaptcha()
        me.getSmsCode()
        $('#getCaptcha').on('click', function(event) {
          event.preventDefault();
          /* Act on the event */
          me.getCaptcha()
        });
      }
      $('.content-wrap select[name*="defined"]').forEach((item) => {
        $(item).siblings('input[type=hidden]').val($(item).find('option').not(function () { return !this.selected }).text())
      })
      $('.content-wrap select[name*="defined"]').change(function (event) {
        $(this).siblings('input[type=hidden]').val($(this).find('option').not(function () { return !this.selected }).text())
      })
    },
    // 获取图片验证码
    getCaptcha: function () {
      let me = this
      $.ajax({
        url: '/api/validate/getcaptcha',
        type: 'GET',
        dataType: 'json',
        data: {},
        success: function (res) {
          if (res.code == 1) {
            me.getSmsObj.captchaKey = res.data.key
            $('#getCaptcha').attr('src', 'data:image/png;base64,' + res.data.base64Image);
          }
        }
      })
    },
    // 获取手机验证码
    getSmsCode: function () {
      let me = this
      $('#getVcode').on('click', function(event) {
        event.preventDefault();
        /* Act on the event */
        let _self = $(this)
        if (_self.hasClass('disabled')) {
          return false
        }
        me.getSmsObj.mobile = $(this).parents('.cont-item').find('input[tip="mobile"]').val()
        // me.getSmsObj.captcheCode = $('#imgCode').val()
        // if ($('#imgCode').val() === '') {
        //   alert('图片验证码不能为空')
        //   return false
        // }
        if (!/^1[34578]\d{9}$/.test(me.getSmsObj.mobile)) {
          alert('请输入正确的手机号')
          return false
        }
        _self.addClass('disabled')
        $.ajax({
          // url: '/api/validate/sendvcodesms',
          url: '/cloud/sms/sms/validCodeSend',
          type: 'GET',
          dataType: 'json',
          data: me.getSmsObj,
          success: function (res) {
            if (res.code == 1) {
              me.countDownFn(_self)
              alert('验证码发送成功')
            } else {
              alert(res.msgZ)
              _self.removeClass('disabled')
            }
          },
          error: function() {
            _self.removeClass('disabled')
          }
        })
      })
    },
    /*倒计时*/
    countDownFn:function(obj){
        obj.addClass('disabled');
        var time = 60;
        var timer = setInterval(function () {
            --time;
            if (time == 0) {
                obj.text('获取验证码');
                obj.removeClass('disabled');
                clearInterval(timer);
            } else {
                obj.text(time + 's重新获取');
            }
        }, 1000)
    },
    submitClick: function () {
      let me = this
      $('.form-btn, .pay-btn').on('click', function (event) {
        event.preventDefault()
        var clickType, ajaxUrl, btnId, payData, payObj;
        let _self = $(this)
        if (window._submit === false) return
        if (_self.hasClass('disabled')) {
          return false
        }
        me.checkRequire()
        if (this.className === 'form-btn') {
          clickType = 'form'
          ajaxUrl = $('#formSubmitUrl').val()
        } else {
          clickType = 'pay'
          ajaxUrl = $('#paySubmitUrl').val()
          btnId = $(this).attr('id')
          payData = payDataStr.split('t|c|l')
          payObj = JSON.parse(payData[btnId.split('_')[1]])
          window._pay_card_id = payObj.ticket
        }
        $('.cont-item').forEach((item, index) => {
          let key = ''
          let val = ''
          let o = {}
          // text
          if ($(item).find('input[type=text]').length > 0 || $(item).find('input[type=date]').length > 0) {
            let elem = $(item).find('input')
            key = elem.attr('name')
            val = elem.val()
            o = {
              name: key,
              type: 'text',
              value: val
            }
            if (elem.attr('tip') === 'mobile') {
              o.tip = 'tel'
              me.params.data.push({
                name: '手机验证码',
                type: 'text',
                value: $('#smsCode').val(),
                tip: 'vCode'
              })
            }
          }
           // textarea
          if ($(item).find('textarea').length > 0) {
            let elem = $(item).find('textarea')
            key = elem.attr('name')
            val = elem.val()
            o = {
              name: key,
              type: 'text',
              value: val
            }
          }
          // 自定义下拉框
          if ($(item).find('select').length > 0) {
            let elem = $(item).find('input[type=hidden]')
            key = elem.attr('name')
            val = elem.val() // $(item).val()
            o = {
              name: key,
              type: 'select',
              value: val
            }
          }
          // radio
          if ($(item).find('input[type=radio]').length > 0) {
            key = $(item).find('input[type=radio]').eq(0).attr('name')
            val = $(item).find('input[type=radio]:checked').val()
            o = {
              name: key,
              type: 'radio',
              value: val
            }
          }
          // checkbox
          if ($(item).find('input[type=checkbox]').length > 0) {
            key = $(item).find('input[type=checkbox]').eq(0).attr('name')
            val = []
            $(item).find('input[type=checkbox]:checked').each(function (index, item) {
              val.push($(this).val())
            })
            o = {
              name: key,
              type: 'multiple',
              values: val
            }
          }
          // file
          if ($(item).find('input[type=file]').length > 0) {
            key = $(item).find('input[type=file]').attr('name')
            val = me.fileData // $(item).val()
            o = {
              name: key && key.replace('upload', ''),
              type: 'image',
              values: val
            }
          }
          me.params.data.push(o)
          if ($(item).find('span.cont-item-required').length > 0) {
            me.requiredArr[key] = val
            let sms = $(item).find('#smsCode')
            if (sms.length > 0){
              me.requiredArr['手机验证码'] = $('#smsCode').val()
            }
          }
        })
        for (var k in me.requiredArr) {
          if (!me.requiredArr[k] || me.requiredArr[k].length < 1) {
            alert('带*号为必填')
            return false
          }
          var val = me.requiredArr[k]
          // if(k === '姓名' && !me.isChinese(val)) {
          //   alert('姓名必须为汉字！')
          //   return false
          // }
          if(k === '手机号码' && !me.isTelNumber(val)) {
            alert('手机号码格式不正确！')
            return false
          }
        }
        _self.addClass('disabled')
        $.ajax({
          url: ajaxUrl,
          type: 'POST',
          data: window.JSON.stringify(me.params),
          contentType: 'application/json',
          dataType: 'json',
          cache: false,
          // processData: false,
          // contentType: false,
          success: function (data) {
            _self.removeClass('disabled')
            if (data.code === 1) {
              if (clickType === 'form') {
                _$UB && _$UB.submit && _$UB.submit()
                switch (afterSubmit.type) {
                  case 1: $('.form-btn').hide().parent().html(afterSubmit.showText); break
                  case 2: location.href = afterSubmit.toWebpage; break
                  case 3: location.href = afterSubmit.toWepage; break
                }
              } else {
                _um_weixin_sdk.pay(
                  payObj.payVal*100,
                  payObj.ticketName,
                  _um_weixin_sdk.getChannel(),
                  data.data.mobile
                  )
              }
            } else {
              alert(data.msgZ)
            }
          },
          error: function () {
            _self.removeClass('disabled')
          }
        })
      })
    },
    checkRequire: function () {
      this.params.data = []
      $('input, textarea').forEach((item) => {
        if (item.id!='imgCode' && $(item).parents('.cont-item').find('span.cont-item-required').length > 0) {
          let key = item.name
          if (!this.requiredArr[key]) {
            this.requiredArr[key] = null
          }
        }
      })
      $('select').forEach((item) => {
        if ($(item).parents('.cont-item').find('span.cont-item-required').length > 0) {
          let key = $(item).siblings('input[type="hidden"]').attr('name')
          if (!this.requiredArr[key]) {
            this.requiredArr[key] = null
          }
        }
      })
    },
    getFileData: function () {
      let me = this
      $('.upload-input').on('change', function (event) {
        event.preventDefault()
        if (me.fileData.length >= 5) {
          alert('最多只能上传5张图片！')
          return
        }
        var file = this.files[0]
        // 判断类型是不是图片
        if (!/image\/\w+/.test(file.type)) {
          alert('请确保文件为图像类型')
          return false
        }
        if (me.fileArr.indexOf(file.name) > -1) {
          alert('已上传过该图片，请重新选择')
          return
        }
        me.fileArr.push(file.name)
        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function (e) {
          // console.log(this.result)  // 就是base64
          me.fileData.push(this.result.split(',')[1])
          $('.file-list').append(`<li class="cl"><span>${file.name}</span><a href="javascript:;">X</a></li>`)
        }
      })
      $('.file-list').on('click', 'a', function (event) {
        event.preventDefault()
        let n = $('.file-list a').index(this)
        $(this).parent('li').remove()
        me.fileData.splice(n, 1)
        me.fileArr.splice(n, 1)
      })
    },
    initArea: function () {
      let len = areaData.length
      if (len > 0) {
        let provienceOptions = ''
        for (let i = 0; i < len; i++) {
          provienceOptions += `<option value="${areaData[i].code}">${areaData[i].name}</option>`
        }
        let areaSelect = $('select[name^="area0"]')
        areaSelect.append(provienceOptions)
        this.provienceChange()
        if (areaSelect.parents('.cont-item').find('span.cont-item-required').length > 0) {
          this.requiredArr[areaSelect.siblings('input[type="hidden"]').attr('name')] = ''
        }
      }
    },
    provienceChange: function () {
      let me = this
      let len = areaData.length
      $('select[name^="area0"]').change(function (event) {
        me.area = ''
        me.provCode = $(this).val()
        me.provText = $(this).find('option').not(function () { return !this.selected }).text()
        if (me.provCode) {
          for (let i = 0; i < len; i++) {
            if (areaData[i].code === me.provCode + '') {
              me.cityData = areaData[i].childs
              me.initCity()
              break
            }
          }
        } else {
          $('select[name^="area1"]').html('<option value="">请选择您所在城市</option>')
          $('select[name^="area2"]').html('<option value="">请选择您所在区县</option>')
          $(this).siblings('input[type="hidden"]').val('')
        }
        if ($(this).parents('.cont-item').find('span.cont-item-required').length > 0) {
          me.requiredArr[$(this).siblings('input[type="hidden"]').attr('name')] = ''
        }
      })
    },
    initCity: function () {
      let len = this.cityData.length
      if (len > 0) {
        let cityOptions = ''
        $('select[name^="area1"]').html('<option value="">请选择您所在城市</option>')
        $('select[name^="area2"]').html('<option value="">请选择您所在区县</option>')
        for (let i = 0; i < len; i++) {
          cityOptions += `<option value="${this.cityData[i].code}">${this.cityData[i].name}</option>`
        };
        $('select[name^="area1"]').append(cityOptions)
        this.cityChange()
      }
    },
    cityChange: function () {
      let me = this
      let len = me.cityData.length
      $('select[name^="area1"]').change(function (event) {
        me.area = ''
        me.cityCode = $(this).val()
        me.cityText = $(this).find('option').not(function () { return !this.selected }).text()
        if (me.cityCode) {
          for (let i = 0; i < len; i++) {
            if (me.cityData[i].code === me.cityCode + '') {
              me.districtData = me.cityData[i].childs
              me.initDistrict()
              break
            }
          }
        } else {
          $('select[name^="area2"]').html('<option value="">请选择您所在区县</option>')
          $(this).siblings('input[type="hidden"]').val('')
        }
        if ($(this).parents('.cont-item').find('span.cont-item-required').length > 0) {
          me.requiredArr[$(this).siblings('input[type="hidden"]').attr('name')] = ''
        }
      })
    },
    initDistrict: function () {
      let len = this.districtData.length
      if (len > 0) {
        let distriOptions = ''
        $('select[name^="area2"]').html('<option value="">请选择您所在区县</option>')
        for (let i = 0; i < len; i++) {
          distriOptions += `<option value="${this.districtData[i].code}">${this.districtData[i].name}</option>`
        };
        $('select[name^="area2"]').append(distriOptions)
        this.districChange()
      }
    },
    districChange: function () {
      let me = this
      $('select[name^="area2"]').change(function (event) {
        if ($(this).val()) {
          me.area = me.provText + me.cityText + $(this).find('option').not(function () { return !this.selected }).text()
          let sibling = $(this).siblings('input[type="hidden"]')
          sibling.val(me.area)
          let o = {
            name: sibling.attr('name'),
            type: 'select',
            value: me.area
          }
          me.params.data.push(o)
        } else {
          me.area = ''
          $(this).siblings('input[type="hidden"]').val('')
        }
        if ($(this).parents('.cont-item').find('span.cont-item-required').length > 0) {
          me.requiredArr[sibling.attr('name')] = me.area
        }
      })
    },
    isChinese: function(value) {
      return /^[\u4E00-\u9FA5]+$/.test(value)
    },
    isTelNumber: function(value) {
      return /^1[3456789]\d{9}$/.test(value)
    },
    isEmail: function(value) {
      return /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)
    }
  }
}
export default {exec}
